<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /* 
      正+负=target
      正-负=sum
      正=(target+sum)/2
      转化思路：
      物品nums，每个物品可以取一次，背包容量为(target+sum)/2,问装满背包有几种方式
        转化为01背包组合问题，dp[0]=1
      */
      var findTargetSumWays = function (nums, target) {
        let sum = nums.reduce((pre, item) => (pre += item))
        if (Math.abs(target) > sum) return 0
        if ((target + sum) % 2) return 0

        let bagSize = (sum + target) / 2

        let dp = new Array(bagSize + 1).fill(0)
        dp[0] = 1
        for (let i = 0; i < nums.length; i++) {
          for (let j = bagSize; j >= nums[i]; j--) {
            dp[j] += dp[j - nums[i]]
          }
        }
        return dp[bagSize]
      }
    </script>
  </body>
</html>
